package manager

import (
	"BlazeRider-backend/app/db"
	"database/sql"
	"fmt"
	"log"
)

// LiveRoomMysqlStorage 管理直播间的状态
type LiveRoomMysqlStorage struct {
}

type LiveRoomMysqlInfo struct {
	LiveRoomId   string       `db:"live_room_id"`
	State        string       `db:"state"`
	Times        int          `db:"times"`
	AnchorOpenId string       `db:"anchor_open_id"`
	AvatarUrl    string       `db:"avatar_url"`
	NickName     string       `db:"nick_name"`
	StartAt      sql.NullTime `db:"start_at"`  // 使用 NullTime
	EndAt        sql.NullTime `db:"end_at"`    // 使用 NullTime
	CreateAt     sql.NullTime `db:"create_at"` // 使用 NullTime
	UpdateAt     sql.NullTime `db:"update_at"` // 使用 NullTime
}

type LiveTrackUserMysqlInfo struct {
	LiveRoomId string       `db:"live_room_id"`
	UserId     string       `db:"user_id"`
	Times      int          `db:"times"`
	Track      int          `db:"track"`
	Job        int          `db:"job"`
	CreateAt   sql.NullTime `db:"create_at"` // 使用 NullTime
	UpdateAt   sql.NullTime `db:"update_at"` // 使用 NullTime
}

type LiveTrackWithUserMysqlInfo struct {
	LiveRoomId   string       `db:"live_room_id"`
	UserId       string       `db:"user_id"`
	Times        int          `db:"times"`
	Track        int          `db:"track"`
	Job          int          `db:"job"`
	UserName     string       `db:"user_name"`
	UserHeadImg  string       `db:"head_img"`
	UserLevel    int          `db:"level"`
	UserScore    int          `db:"score"`
	UserExpireAt sql.NullTime `db:"expire_at"`
	CreateAt     sql.NullTime `db:"create_at"` // 使用 NullTime
	UpdateAt     sql.NullTime `db:"update_at"` // 使用 NullTime
}

// LiveRoomResultMysqlInfo 表示 live_room_result 表的结构
type LiveRoomResultMysqlInfo struct {
	LiveRoomID   string       `db:"live_room_id"`
	Times        int          `db:"times"`
	UserID       string       `db:"user_id"`
	GameScore    int          `db:"game_score"`
	Track        int          `db:"track"`
	Job          int          `db:"job"`
	IsChampion   int          `db:"is_champion"`
	IsFinish     int          `db:"is_finish"`
	IsBiggest    int          `db:"is_biggest"`
	GiftValue    int          `db:"gift_value"`
	GiftScore    int          `db:"gift_score"`
	GetScore     int          `db:"get_score"`
	HasDone      int          `db:"has_done"`
	UserName     string       `db:"user_name"`
	HeadImg      string       `db:"head_img"`
	UserLevel    int          `db:"user_level"`
	UserScore    int          `db:"user_score"`
	TargetLevel  int          `db:"target_level"`
	TargetScore  int          `db:"target_score"`
	Mileage      int          `db:"mileage"`
	JumpHeight   float32      `db:"jump_height"`
	FinishTime   int          `db:"jump_height"`
	FinishTime1  int          `db:"jump_height1"`
	FinishTime2  int          `db:"jump_height2"`
	FastestSpeed int          `db:"jump_height"`
	AttackPower  int          `db:"attack_power"`
	ExpireAt     sql.NullTime `db:"expire_at"`
	CreateAt     sql.NullTime `db:"create_at"`
	UpdateAt     sql.NullTime `db:"update_at"`
	TotalRank    int          `db:"total_rank"`
}

type GameDataMysqlInfo struct {
	LiveRoomId string       `db:"live_room_id"`
	Times      string       `db:"times"`
	RawData    string       `db:"raw_data"`
	CreateAt   sql.NullTime `db:"create_at"` // 使用 NullTime
	UpdateAt   sql.NullTime `db:"update_at"` // 使用 NullTime
}

func NewLiveRoomMysqlStorage() (*LiveRoomMysqlStorage, error) {

	return &LiveRoomMysqlStorage{}, nil
}

// 创建直播间数据
func (lrm *LiveRoomMysqlStorage) CreateLiveRoom(liveRoomID, AnchorOpenId, AvatarUrl, NickName string, state string, times int) error {
	_, err := db.GetDB().Exec(`
		INSERT INTO live_room 
			(live_room_id, anchor_open_id, avatar_url, nick_name, state, times, create_at, update_at)
		VALUES 
			(?, ?, ?, ?,  ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
		`,
		liveRoomID, AnchorOpenId, AvatarUrl, NickName, state, times) // 更新值参数

	if err != nil {
		return fmt.Errorf("create live room error : %v", err)
	}
	return nil
}

// SetLiveRoomState 设置直播间的状态
func (lrm *LiveRoomMysqlStorage) SetLiveRoomState(liveRoomID string, isInGame bool) error {
	liveRoomMysqlInfo, err := lrm.GetLiveRoom(liveRoomID)

	var gameStateStr string
	if err == nil {
		if isInGame {
			gameStateStr = "start"
		} else {
			gameStateStr = "end"
		}

		// 如果直播间状态与要设置的状态一致，则不做处理，返回操作成功
		if liveRoomMysqlInfo.State == gameStateStr && !isInGame {
			return nil
		}

		liveRoomMysqlInfo.State = gameStateStr
		if isInGame {
			liveRoomMysqlInfo.Times++
		}

		lrm.SetLiveRoom(liveRoomMysqlInfo.LiveRoomId, liveRoomMysqlInfo.State, liveRoomMysqlInfo.Times)
		return nil
	}

	times := 0
	if isInGame {
		gameStateStr = "start"
		times = 1
	} else {
		gameStateStr = "end"
	}

	err = lrm.CreateLiveRoom(liveRoomID, "", "", "", gameStateStr, times)
	if err != nil {
		return fmt.Errorf("failed to initialize user: %v", err)
	}
	return nil
}

// SetLiveRoomState 设置直播间的状态
func (lrm *LiveRoomMysqlStorage) CreateLiveRoomIfNotExist(liveRoomID, AnchorOpenId, AvatarUrl, NickName string) (string, error) {
	liveRoomMysqlInfo, err := lrm.GetLiveRoom(liveRoomID)

	if err == nil {
		return liveRoomMysqlInfo.LiveRoomId, nil
	}

	err = lrm.CreateLiveRoom(liveRoomID, AnchorOpenId, AvatarUrl, NickName, "end", 0)
	if err != nil {
		return "", fmt.Errorf("failed to initialize user: %v", err)
	}
	return liveRoomID, nil
}

// GetLiveRoomState 获取直播间的状态
func (lrm *LiveRoomMysqlStorage) GetLiveRoomState(liveRoomID string) (string, error) {
	liveRoomMysqlInfo, err := lrm.GetLiveRoom(liveRoomID)

	if err != nil {
		return "", err
	}

	return liveRoomMysqlInfo.State, nil
}

func (lrm *LiveRoomMysqlStorage) GetLiveRoom(liveRoomID string) (*LiveRoomMysqlInfo, error) {
	// 定义一个变量来存储查询结果
	var liveRoom LiveRoomMysqlInfo

	// 执行 SQL 查询
	err := db.GetDB().QueryRow(`
        SELECT live_room_id, anchor_open_id, avatar_url, nick_name, state, times, start_at, end_at, create_at, update_at
        FROM live_room
        WHERE live_room_id = ?
    `, liveRoomID).Scan(
		&liveRoom.LiveRoomId,
		&liveRoom.AnchorOpenId,
		&liveRoom.AvatarUrl,
		&liveRoom.NickName,
		&liveRoom.State,
		&liveRoom.Times,
		&liveRoom.StartAt,
		&liveRoom.EndAt,
		&liveRoom.CreateAt,
		&liveRoom.UpdateAt,
	)

	// 处理错误
	if err != nil {
		if err == sql.ErrNoRows {
			log.Printf("No live room found in GetLiveRoom with ID: %s", liveRoomID)
			return nil, err // 没有找到数据，返回 ErrNoRows
		}
		log.Printf("Error querying GetLiveRoom: %v", err) // 打印其他错误信息
		return nil, err                                   // 返回其他错误
	}

	// 查询成功，返回结果
	return &liveRoom, nil
}

// SetLiveRoomstate 设置直播间的状态
func (lrm *LiveRoomMysqlStorage) SetLiveRoom(liveRoomID string, state string, times int) error {
	query := ""
	if state == "start" {
		query = `
		update live_room
		set state = ?,
			times = ?,
			start_at = CURRENT_TIMESTAMP,
			update_at = CURRENT_TIMESTAMP
		where
		    live_room_id = ?
	`
	} else if state == "end" {
		query = `
		update live_room
		set state = ?,
			times = ?,
			end_at = CURRENT_TIMESTAMP,
			update_at = CURRENT_TIMESTAMP
		where
		    live_room_id = ?
	`
	}
	_, err := db.GetDB().Exec(query,
		state, times, liveRoomID) // 更新值参数

	if err != nil {
		return fmt.Errorf("set live room error: %v", err)
	}
	return nil
}

// 创建直播间的用户设定阵营数据
func (lrm *LiveRoomMysqlStorage) CreateLiveTrack(liveRoomID string, userId string, times int, track int, job int) error {
	_, err := db.GetDB().Exec(`
		INSERT INTO live_track 
			(live_room_id, user_id, times, track, job, create_at, update_at)
		VALUES 
			(?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
		`,
		liveRoomID, userId, times, track, job) // 更新值参数

	if err != nil {
		return fmt.Errorf("create live track error : %v", err)
	}
	return nil
}

func (lrm *LiveRoomMysqlStorage) GetLiveTrackByUserId(liveRoomId string, userId string, times int) (*LiveTrackUserMysqlInfo, error) {
	// 定义一个变量来存储查询结果
	var liveTrackUserMysqlInfo LiveTrackUserMysqlInfo

	// 执行 SQL 查询
	err := db.GetDB().QueryRow(`
        SELECT live_room_id, user_id, times, track, job, create_at, update_at
        FROM live_track
        WHERE live_room_id = ? and
               user_id = ? and
                times = ? 
    `, liveRoomId, userId, times).Scan(
		&liveTrackUserMysqlInfo.LiveRoomId,
		&liveTrackUserMysqlInfo.UserId,
		&liveTrackUserMysqlInfo.Times,
		&liveTrackUserMysqlInfo.Track,
		&liveTrackUserMysqlInfo.Job,
		&liveTrackUserMysqlInfo.CreateAt,
		&liveTrackUserMysqlInfo.UpdateAt,
	)

	// 处理错误
	if err != nil {
		if err == sql.ErrNoRows {
			log.Printf("No live room found in GetLiveTrackByUserId with ID: %s, user_id: %s, times: %d", liveRoomId, userId, times)
			return nil, err // 没有找到数据，返回 ErrNoRows
		}
		log.Printf("Error querying in GetLiveTrackByUserId live track: %v", err) // 打印其他错误信息
		return nil, err                                                          // 返回其他错误
	}

	// 查询成功，返回结果
	return &liveTrackUserMysqlInfo, nil
}

// 设置直播间用户参加阵营的数据
func (lrm *LiveRoomMysqlStorage) JoinLiveRoomTrackMysql(liveRoomId string, times int, state string, userId string, track int, job int) (*LiveTrackUserMysqlInfo, error) {
	//liveRoomMysqlInfo, err := lrm.GetLiveRoom(liveRoomId)
	//if err != nil {
	//	return nil, fmt.Errorf("join live room track error : %v, by no live room", err)
	//}

	if state == "end" {
		return nil, fmt.Errorf("join live room track error because live room state is end")
	}

	liveTrackUserMysqlInfo, err := lrm.GetLiveTrackByUserId(liveRoomId, userId, times)

	if err == nil {
		return liveTrackUserMysqlInfo, fmt.Errorf("user has join live room track ")
	}

	err = lrm.CreateLiveTrack(liveRoomId, userId, times, track, job)
	if err != nil {
		return nil, fmt.Errorf("failed to initialize user live track: %v", err)
	}

	return liveTrackUserMysqlInfo, nil
}

// 设置直播间用户参加阵营的数据
func (lrm *LiveRoomMysqlStorage) GetLiveRoomTrackMysql(liveRoomId string, userId string) (*LiveTrackUserMysqlInfo, error) {
	liveRoomMysqlInfo, err := lrm.GetLiveRoom(liveRoomId)

	if err != nil {
		return nil, fmt.Errorf("join live room track error : %v, by no live room", err)
	}

	//if liveRoomMysqlInfo.State == "end" {
	//	return nil, fmt.Errorf("join live room track error : %v, by live room state is end", err)
	//}

	liveTrackUserMysqlInfo, err := lrm.GetLiveTrackByUserId(liveRoomId, userId, liveRoomMysqlInfo.Times)

	if err != nil {
		return nil, err
	}

	return liveTrackUserMysqlInfo, nil

}

// 查询用户参与阵营的数据，关联用户数据
func (lrm *LiveRoomMysqlStorage) GetLiveTrackInfosWithUserInfoByTime(liveRoomId string, times int, timeStr string) ([]LiveTrackWithUserMysqlInfo, error) {
	query := fmt.Sprintf(`
       SELECT lt.live_room_id, lt.user_id, lt.times, lt.track, lt.job, lt.create_at, lt.update_at,
              us.user_name, us.head_img, us.level, us.score, us.expire_at
       FROM live_track lt
       left join users us on us.user_id = lt.user_id
       WHERE lt.live_room_id = ? and
              lt.times = ? and
               lt.create_at >= ? 
    `)

	// 准备查询参数
	args := make([]interface{}, 0, 3)
	args = append(args, liveRoomId)
	args = append(args, times)
	args = append(args, timeStr)

	// 查询数据
	rows, err := db.GetDB().Query(query, args...)
	if err != nil {
		log.Printf("Error querying gift records: %v", err)
		return nil, err
	}
	defer rows.Close()

	// 遍历查询结果
	var liveTrackUserMysqlInfoList []LiveTrackWithUserMysqlInfo
	for rows.Next() {
		var record LiveTrackWithUserMysqlInfo
		if err := rows.Scan(
			&record.LiveRoomId,
			&record.UserId,
			&record.Times,
			&record.Track,
			&record.Job,
			&record.CreateAt,
			&record.UpdateAt,
			&record.UserName,
			&record.UserHeadImg,
			&record.UserLevel,
			&record.UserScore,
			&record.UserExpireAt,
		); err != nil {
			log.Printf("Error scanning gift record: %v", err)
			return nil, err
		}
		liveTrackUserMysqlInfoList = append(liveTrackUserMysqlInfoList, record)
	}

	return liveTrackUserMysqlInfoList, nil
}

// BatchInsertLiveRoomResults 批量插入直播间的比赛结果到数据库
func (lrm *LiveRoomMysqlStorage) BatchInsertLiveRoomResults(results []LiveRoomResultMysqlInfo) error {
	stmt, err := db.GetDB().Prepare(`INSERT INTO live_room_result (
		live_room_id, times, user_id, game_score, track, job, is_champion, is_finish, is_biggest, gift_value, gift_score, 
    	get_score, has_done, user_name, head_img, user_level, user_score, target_level, target_score,
        mileage, jump_height, finish_time, finish_time1, finish_time2, fastest_speed, attack_power,
        expire_at, create_at, update_at
	) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
	if err != nil {
		return fmt.Errorf("prepare statement error: %v", err)
	}
	defer stmt.Close()

	for _, result := range results {
		_, err := stmt.Exec(
			result.LiveRoomID, result.Times, result.UserID, result.GameScore, result.Track, result.Job,
			result.IsChampion, result.IsFinish, result.IsBiggest, result.GiftValue, result.GiftScore, result.GetScore,
			result.HasDone, result.UserName, result.HeadImg, result.UserLevel, result.UserScore,
			result.TargetLevel, result.TargetScore, result.Mileage, result.JumpHeight,
			result.FinishTime, result.FinishTime1, result.FinishTime2, result.FastestSpeed, result.AttackPower,
			result.ExpireAt,
		)
		if err != nil {
			return fmt.Errorf("insert error: %v", err)
		}
	}

	return nil
}

// GetGiftRecordByliveRoomAdnTrack 查询本局最后一次该礼物信息
func (lrm *LiveRoomMysqlStorage) GetLiveRoomResults(liveRoomId string, times int) ([]LiveRoomResultMysqlInfo, error) {
	// 构建查询语句
	query := fmt.Sprintf(`
		SELECT lrr.live_room_id, lrr.times, lrr.user_id, lrr.game_score, lrr.track,
			   lrr.is_champion, lrr.is_finish, lrr.gift_value, lrr.gift_score, 
			   lrr.get_score, lrr.has_done, 
			   lrr.create_at, lrr.update_at,
			   lrr.user_name, lrr.head_img, lrr.user_level,
			   lrr.user_score, lrr.target_level, lrr.target_score, 
			   lrr.mileage, lrr.jump_height, lrr.finish_time, lrr.fastest_speed, lrr.attack_power,
			   lrr.expire_at
		FROM live_room_result lrr
		WHERE lrr.live_room_id = ? AND lrr.times = ? 
	`)

	// 准备查询参数
	args := make([]interface{}, 0, 2)
	args = append(args, liveRoomId)
	args = append(args, times)

	// 查询数据
	rows, err := db.GetDB().Query(query, args...)
	if err != nil {
		log.Printf("Error querying gift records: %v", err)
		return nil, err
	}
	defer rows.Close()

	// 遍历查询结果
	var liveResultMysqlInfoList []LiveRoomResultMysqlInfo
	for rows.Next() {
		var record LiveRoomResultMysqlInfo
		if err := rows.Scan(
			&record.LiveRoomID,
			&record.Times,
			&record.UserID,
			&record.GameScore,
			&record.Track,
			&record.IsChampion,
			&record.IsFinish,
			&record.GiftValue,
			&record.GiftScore,
			&record.GetScore,
			&record.HasDone,
			&record.CreateAt,
			&record.UpdateAt,
			&record.UserName,
			&record.HeadImg,
			&record.UserLevel,
			&record.UserScore,
			&record.TargetLevel,
			&record.TargetScore,
			&record.Mileage,
			&record.JumpHeight,
			&record.FinishTime,
			&record.FastestSpeed,
			&record.AttackPower,
			&record.ExpireAt,
		); err != nil {
			log.Printf("Error scanning gift record: %v", err)
			return nil, err
		}
		liveResultMysqlInfoList = append(liveResultMysqlInfoList, record)
	}

	// 检查是否查询到数据
	if len(liveResultMysqlInfoList) == 0 {
		log.Printf("No gift records found for live room ID: %s", liveRoomId)
		return nil, sql.ErrNoRows
	}

	return liveResultMysqlInfoList, nil
}

// GetLiveRoomResultsForGameRank 获取对局中的用户的排名总数据
func (lrm *LiveRoomMysqlStorage) GetLiveRoomResultsForGameRank(liveRoomId string, times int) ([]LiveRoomResultMysqlInfo, error) {
	// 使用CTE实现用户最佳成绩全局排名[1,3](@ref)
	query := `
        WITH user_max_scores AS (
            SELECT 
                user_id,
                MAX(target_score) AS max_target_score
            FROM live_room_result
            GROUP BY user_id
        ),
        global_ranks AS (
            SELECT 
                user_id,
                max_target_score,
                RANK() OVER (ORDER BY max_target_score DESC) AS global_rank
            FROM user_max_scores
        )
        SELECT 
            lrr.live_room_id, lrr.times, lrr.user_id, lrr.game_score, lrr.track,
            lrr.is_champion, lrr.is_finish, lrr.gift_value, lrr.gift_score, 
            lrr.get_score, lrr.has_done, 
            lrr.create_at, lrr.update_at,
            lrr.user_name, lrr.head_img, lrr.user_level,
            lrr.user_score, lrr.target_level, lrr.target_score, 
            lrr.mileage, lrr.jump_height, lrr.finish_time, lrr.fastest_speed, 
            lrr.attack_power, lrr.expire_at,
            gr.global_rank  -- 添加全局排名字段
        FROM live_room_result lrr
        JOIN global_ranks gr ON lrr.user_id = gr.user_id
        WHERE lrr.live_room_id = ? AND lrr.times = ?
    `

	// 使用预编译语句防止SQL注入[1,4](@ref)
	stmt, err := db.GetDB().Prepare(query)
	if err != nil {
		log.Printf("Error preparing query: %v", err)
		return nil, err
	}
	defer stmt.Close()

	// 执行带参数的查询[2,5](@ref)
	rows, err := stmt.Query(liveRoomId, times)
	if err != nil {
		log.Printf("Error executing query: %v", err)
		return nil, err
	}
	defer rows.Close()

	var results []LiveRoomResultMysqlInfo
	for rows.Next() {
		var record LiveRoomResultMysqlInfo
		// 添加GlobalRank到Scan序列[3](@ref)
		if err := rows.Scan(
			&record.LiveRoomID,
			&record.Times,
			&record.UserID,
			&record.GameScore,
			&record.Track,
			&record.IsChampion,
			&record.IsFinish,
			&record.GiftValue,
			&record.GiftScore,
			&record.GetScore,
			&record.HasDone,
			&record.CreateAt,
			&record.UpdateAt,
			&record.UserName,
			&record.HeadImg,
			&record.UserLevel,
			&record.UserScore,
			&record.TargetLevel,
			&record.TargetScore,
			&record.Mileage,
			&record.JumpHeight,
			&record.FinishTime,
			&record.FastestSpeed,
			&record.AttackPower,
			&record.ExpireAt,
			&record.TotalRank,
		); err != nil {
			log.Printf("Error scanning row err in GetLiveRoomResultsForGameRank : %v", err)
			return nil, err
		}
		results = append(results, record)
	}

	// 检查遍历过程中的错误[7,8](@ref)
	if err := rows.Err(); err != nil {
		log.Printf("Error iterating rows  in GetLiveRoomResultsForGameRank : %v", err)
		return nil, err
	}

	if len(results) == 0 {
		log.Printf("No records found in GetLiveRoomResultsForGameRank for liveRoomId: %s, times: %d", liveRoomId, times)
		return nil, sql.ErrNoRows
	}

	return results, nil
}

// 创建直播间的用户设定阵营数据
func (lrm *LiveRoomMysqlStorage) SetDoneByCreateAt(dateStr string) error {
	_, err := db.GetDB().Exec(`
		update live_room_result 
			set has_done = 1,
			    update_at = CURRENT_TIMESTAMP
		where create_at <= ?
		`,
		dateStr) // 更新值参数

	if err != nil {
		return fmt.Errorf("create live track error : %v", err)
	}
	return nil
}
func (lrm *LiveRoomMysqlStorage) GetLiveRoomFailGiftInfoWhenStart() ([]LiveRoomMysqlInfo, error) {
	// 直接使用参数化查询，无需通过 fmt.Sprintf 格式化
	query := `
        SELECT 
            lr.live_room_id, 
            lr.state, 
            lr.times, 
            lr.anchor_open_id, 
            lr.avatar_url,
            lr.nick_name
        FROM 
            live_room lr
        WHERE 
            lr.state = ?  
    `

	// 参数需传入对应 "start" 的值
	args := []interface{}{"start"}

	// 执行查询时传入参数
	rows, err := db.GetDB().Query(query, args...)
	if err != nil {
		log.Printf("Error querying gift records: %v", err)
		return nil, err
	}
	defer rows.Close()

	// 后续循环逻辑保持不变...
	var liveRoomMysqlInfoList []LiveRoomMysqlInfo
	for rows.Next() {
		var record LiveRoomMysqlInfo
		if err := rows.Scan(
			&record.LiveRoomId,
			&record.State,
			&record.Times,
			&record.AnchorOpenId,
			&record.AvatarUrl,
			&record.NickName,
		); err != nil {
			log.Printf("Error scanning gift record: %v", err)
			return nil, err
		}
		liveRoomMysqlInfoList = append(liveRoomMysqlInfoList, record)
	}

	// 处理空结果时建议直接返回空数组，而非 sql.ErrNoRows
	return liveRoomMysqlInfoList, nil
}

// SetLiveRoomState 设置直播间的状态
func (lrm *LiveRoomMysqlStorage) SetLiveRoomFailGiftNum(liveRoomID string, pageNum, pageNumWhole int) error {
	_, err := db.GetDB().Exec(`
		update live_room
		set fail_gift_page_num = ?,
			fail_gift_whole_page = ?,
			update_at = CURRENT_TIMESTAMP
		where
		    live_room_id = ?
	`,
		pageNum, pageNumWhole, liveRoomID) // 更新值参数

	if err != nil {
		return fmt.Errorf("set live room error: %v", err)
	}
	return nil
}

// 插入直播间数据
func (lrm *LiveRoomMysqlStorage) InsertGameDate(liveRoomID string, times int, rawData string) error {
	_, err := db.GetDB().Exec(`
		INSERT INTO game_detail_data 
			(live_room_id, times, raw_data, create_at, update_at)
		VALUES 
			(?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
		`,
		liveRoomID, times, rawData) // 更新值参数

	if err != nil {
		return fmt.Errorf("insert Game Date error : %v", err)
	}
	return nil
}

// 获取直播间数据
func (lrm *LiveRoomMysqlStorage) GetGameDate(liveRoomID string, times int) (*GameDataMysqlInfo, error) {
	var gameData GameDataMysqlInfo

	err := db.GetDB().QueryRow(`
        SELECT live_room_id, times, raw_data, create_at, update_at
        FROM game_detail_data
        WHERE live_room_id = ? 
			and times = ?
		order by id desc limit 1
    `, liveRoomID, times).Scan(
		&gameData.LiveRoomId,
		&gameData.Times,
		&gameData.RawData,
		&gameData.CreateAt,
		&gameData.UpdateAt,
	)

	// 处理错误
	if err != nil {
		if err == sql.ErrNoRows {
			log.Printf("No live room found in GetGameDate with ID: %s", liveRoomID)
			return nil, err // 没有找到数据，返回 ErrNoRows
		}
		log.Printf("Error querying GetGameDate : %v", err) // 打印其他错误信息
		return nil, err                                    // 返回其他错误
	}

	// 查询成功，返回结果
	return &gameData, nil
}
